import * as CryptoJS from "crypto-js";

export const checkStrLengthIsNotZero = (str) => {
    return str.split(' ').join('').length !== 0
}


export const validateIDCard = (idCard) => {
    const regex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/;
    return regex.test(idCard);
}


export function debounceImmediate(fn, delay = 1000) {

    let timer = null;
    return function(...args) {
        clearTimeout(timer); // 清除之前的定时器
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, delay);
    };
}


/**
 *加密处理
 */
export const encryption = (params) => {
    let {
        data,
        type,
        param,
        key
    } = params;
    const result = JSON.parse(JSON.stringify(data));
    if (type === "Base64") {
        param.forEach((ele) => {
            result[ele] = btoa(result[ele]);
        });
    } else {
        param.forEach((ele) => {
            var data = result[ele];
            key = CryptoJS.enc.Latin1.parse(key);
            var iv = key;
            // 加密 
            var encrypted = CryptoJS.AES.encrypt(data, key, {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.ZeroPadding,
            });
            result[ele] = encrypted.toString();
        });
    }
    return result;
};

export function obj2query(obj) {
    // 首先判断obj是否为真，为真则进行处理，不然直接return
    if (obj) {
        // 定义变量接收query字符串
        let query = ""
        // 循环遍历对象
        for (let i in obj) {
            // 定义变量接收对象的value值
            let value = obj[i]
            // 若对象的value值为数组，则进行join打断
            if (Array.isArray(value)) {
                value = value.join(",")
            }
            // 进行字符串拼接
            query += `&${i}=${value}`
        }
        // replace返回一个新的字符串，要用query重新接受一下，并把第一个&替换为?
        query = query.replace('&', '?')
        // 返回生成的query字符串
        return query
    }
    return ""
}